<template>
  <div class="attr-item">
    <div class="attr-item-label">
      <span>{{ title }}</span>
    </div>
    <div class="attr-item-value">
      <a-button type="primary"> 绑定动作 </a-button>

      <a-modal
        v-model:open="curVisible"
        :width="width"
        :title="title"
        @ok="modalOk"
      >
        <div
          :style="{
            height: height,
          }"
          ref="editorContainerVarRule"
        ></div>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, nextTick, toRaw } from 'vue'

import { BwDesignVarRuleProps as curProps } from './props'

import * as monaco from 'monaco-editor'
import BwMonacoEditor from '@/utils/monacoEditor'
import { onGetPageCodeTips } from './util'

export default defineComponent({
  name: 'BwNodeAttrsConstConfigCode',
  components: {},
  props: curProps,
  emits: ['update:value', 'update:visible', 'ok'],
  setup(props, { expose, emit }) {
    const bwMonacoEditor = new BwMonacoEditor()

    // #region 值处理
    const curValue = computed({
      get: (): string => {
        let value = props.value ?? ''
        return value
      },
      set: (value: string) => {
        emit('update:value', value)
      },
    })

    const curVisible = computed({
      get: (): boolean => {
        return props.visible ?? false
      },
      set: (value: boolean) => {
        emit('update:visible', value)
      },
    })

    watch(
      () => curVisible.value,
      (newVal) => {
        if (!!newVal) {
          nextTick(() => {
            onCreateEditor()
          })
        }
      },
      { deep: true, immediate: true }
    )

    // #endregion

    // #region 事件编辑
    const editorContainerVarRule = ref()
    let curEditor = ref<monaco.editor.IStandaloneCodeEditor | undefined>()

    const modalOk = () => {
      let value = ''
      if (curEditor.value) {
        value = toRaw(curEditor.value).getValue()
      }

      emit('ok', value)
      curVisible.value = false
    }

    const onCreateEditor = () => {
      let tips = onGetPageCodeTips(expose, emit)

      curEditor.value = bwMonacoEditor.create({
        domElement: editorContainerVarRule.value,
        options: {
          value: curValue.value,
        },
        tips: tips,
        menus: undefined,
        snippets: undefined,
      })
    }

    return {
      curValue,
      curVisible,

      editorContainerVarRule,
      modalOk,
    }
  },
})
</script>

<style lang="less" scoped></style>
